package com.zhouyu.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhouyu.domain.User;
import com.zhouyu.entity.DemoData;
import com.zhouyu.mapper.UserMapper;
import com.zhouyu.utils.TestFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lipengze
 * @version 1.0
 * @description: TODO
 * @date 2024/11/28 11:42
 */
@Slf4j
@Service
public class PageExcelService {
    @Resource
    private UserMapper userMapper;

    /**
     * 从数据库中查询分页数据
     *
     * @param page  当前页码
     * @param size  每页大小
     * @return  分页数据
     */
    private List<DemoData> data(int page, int size) {
        Page<User> pageObj = new Page<>(page, size);
        IPage<User> pageResult = userMapper.selectPage(pageObj, null);
        List<DemoData> demoDataList = new ArrayList<>();
        for (User user : pageResult.getRecords()) {
            DemoData demoData = new DemoData();
            demoData.setId(user.getId());
            demoData.setName(user.getName());
            demoData.setAge(user.getAge());
            demoData.setSex(user.getSex());
            demoDataList.add(demoData);
        }

        return demoDataList;
    }

    public void export() {
        long t1 = System.currentTimeMillis();

        // 方法2: 如果写到不同的sheet 同一个对象
        String fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 指定文件
        try (ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build()) {
            // 假设总共有100页数据
            int totalPages = 100;
            // 每页大小
            int pageSize = 50000;

            // 循环遍历每一页数据
            for (int i = 1; i <= totalPages; i++) {
                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
                WriteSheet writeSheet = EasyExcel.writerSheet(i - 1, "模板" + (i - 1)).build();
                // 分页查询数据并转换
                List<DemoData> data = data(i, pageSize);
                excelWriter.write(data, writeSheet);
            }
        } catch (Exception e) {
            log.error("Export failed", e);
        }
        long t2 = System.currentTimeMillis();
        log.info("export success, cost time: {} ms", t2 - t1);
    }
}
